package com.dhu.cst.ningtianzhe181310419.test;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.Toolbar;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.dhu.cst.ningtianzhe181310419.test.Json.UserInfo;
import com.google.gson.Gson;
import com.wildma.pictureselector.PictureBean;
import com.wildma.pictureselector.PictureSelector;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangeActivity extends AppCompatActivity {
    public static final String    TAG = "PictureSelector";
    public Bitmap bitmap;
    public ImageView userPhotoChange;
    public EditText nameChange;
    public EditText schoolChange;
    public EditText localeChange;
    public String name,school,locale;
    public SharedPreferences sharedPreferences;
    public SharedPreferences.Editor editor;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change);
        this.getSupportActionBar().hide();
        initView();
        setInformation();
    }

    public void initView(){
        userPhotoChange = this.findViewById(R.id.UserPhotoChange);
        nameChange = this.findViewById(R.id.nameChange);
        schoolChange = this.findViewById(R.id.schoolChange);
        localeChange = this.findViewById(R.id.localeChange);
        sharedPreferences = getSharedPreferences("info",MODE_PRIVATE);
    }
    public void backToMain(View view){
        Intent intent = new Intent();
        intent.setClass(this,MainActivity.class);
        this.startActivity(intent);
    }

    //获取个人信息，并传送给change界面
    public void setInformation(){
        nameChange.setText(ShowActivity.name);
        schoolChange.setText(ShowActivity.school);
        localeChange.setText(ShowActivity.locale);
    }

    public void ChangeUserHead(View view){
        PictureSelector
                .create(ChangeActivity.this, PictureSelector.SELECT_REQUEST_CODE)
                .selectPicture(false);
    }

    //提交
    public void submit(View view){
        ChangeInfo();
        Intent intent = new Intent();
        intent.putExtra("name",name);
        intent.putExtra("school",school);
        intent.putExtra("locale",locale);
        intent.setClass(ChangeActivity.this,ShowActivity.class);
        ChangeActivity.this.startActivity(intent);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
            if (data != null) {
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                Log.i(TAG, "是否裁剪: " + pictureBean.isCut());
                Log.i(TAG, "原图地址: " + pictureBean.getPath());
                Log.i(TAG, "图片 Uri: " + pictureBean.getUri());
                if (pictureBean.isCut()) {
                    userPhotoChange.setImageBitmap(BitmapFactory.decodeFile(pictureBean.getPath()));
                } else {
                    userPhotoChange.setImageURI(pictureBean.getUri());
                }
                //使用 Glide 加载图片
                /*Glide.with(this)
                        .load(pictureBean.isCut() ? pictureBean.getPath() : pictureBean.getUri())
                        .apply(RequestOptions.centerCropTransform()).into(mIvImage);*/

                //实际开发中将图片上传到服务器成功后需要删除全部缓存图片（即裁剪后的无用图片）
                //FileUtils.deleteAllCacheImage(this);
            }
        }
    }

    public void ChangeInfo(){
        if(!nameChange.getText().toString().isEmpty())
            Info.name = nameChange.getText().toString();
        if(!schoolChange.getText().toString().isEmpty())
            Info.school = schoolChange.getText().toString();
        if(!localeChange.getText().toString().isEmpty())
            Info.address = localeChange.getText().toString();
        OkHttpClient okHttpClient = new OkHttpClient();
        UserInfo userInfo = new UserInfo(Info.address,CommonUtil.getTime(),Info.email,0,Info.name,Info.phoneNumber,"办公",Info.phoneNumber);
        Gson gson = new Gson();
        String json = gson.toJson(userInfo);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder()
                .url("http://106.15.200.177:8081/api/contactInfo/update")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ChangeActivity.this,"信息修改册失败！",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ChangeActivity.this,"信息修改成功！",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}
